package org.skydiveapp;

import java.util.List;

import org.skydiveapplibrary.ui.GalleryGridView;
import org.skydiveapplibrary.ui.ImageAdapter;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.Constants;
import org.skydiveapplibrary.data.LogEntry;
import org.skydiveapplibrary.data.LogEntryImage;
import org.skydiveapplibrary.data.LogEntryImageType;
import org.skydiveapplibrary.repository.LogEntryRepository;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.SherlockFragment;


public class GalleryFragment extends SherlockFragment
{
	private ImageAdapter imageAdapter;
	private LogEntryRepository logEntryRepository;
	private LogEntryImage currentEditedImage;
	
	private static final int REQUEST_DIAGRAM = 4;
	private static final int REQUEST_VIEW_PHOTO = 6;
	
	private onLogEntryEditRequestListener mListener;
	
	public interface onLogEntryEditRequestListener {
        public void onLogEntryEditRequest(Bundle args);
    }
	 
	private OnItemClickListener imageEditListener = new AdapterView.OnItemClickListener()
	{
		@Override
		 public void onItemClick(AdapterView<?> parent, View v, int position, long id)
		{
			// set currently edited
			currentEditedImage = imageAdapter.getItem(position);
			if (currentEditedImage.getImageType() == LogEntryImageType.Diagram)
			{
				Intent intent = new Intent(getActivity(), LogEntryDiagramActivity.class);
	            intent.putExtra(Constants.EXTRA_DIAGRAM_FILENAME, currentEditedImage.getFilename());
	            intent.putExtra(Constants.EXTRA_GOTO_LOG_ENTRY, true);
	            startActivityForResult(intent, REQUEST_DIAGRAM);
			}
			else
			{
				Intent intent = new Intent(getActivity(), LogEntryPhotoActivity.class);
	            intent.putExtra(Constants.EXTRA_PHOTO, currentEditedImage.getFilename());
	            intent.putExtra(Constants.EXTRA_GOTO_LOG_ENTRY, true);
	            startActivityForResult(intent, REQUEST_VIEW_PHOTO);
			}
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		logEntryRepository = new LogEntryRepository(getActivity());
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    		Bundle savedInstanceState)
	{	
	    // Inflate the layout for this fragment
        return inflater.inflate(R.layout.gallery_view, container, false);
	}
	
    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        // Check that the container activity has implemented the callback interface
        try {
            mListener = (onLogEntryEditRequestListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() 
                    + " must implement OnItemSelectedListener");
        }
    }
	
	@Override
	public void onResume()
	{
		super.onResume();

		final GalleryGridView galleryView = (GalleryGridView) getActivity().findViewById(R.id.gallery);
	
		galleryView.getViewTreeObserver().addOnGlobalLayoutListener(
    		   new ViewTreeObserver.OnGlobalLayoutListener()
    		   {
    			   public void onGlobalLayout()
    			   {
    				   // When we get here, the size of the frame view is known.
	        		   // Use those dimensions to set the width of the image size.
	        		   if (imageAdapter == null)
	        		   {        			   
	        			   setupGalleryView(galleryView);
        			   }
        		   }
			   });

		if (imageAdapter != null && imageAdapter.getImageSize() > 0 &&
				galleryView.getAdapter() == null)
		{
			setupGalleryView(galleryView);
		}
	}
	
	private void setupGalleryView(GalleryGridView galleryView)
	{
		if (imageAdapter == null)
		{
			   imageAdapter = new ImageAdapter(getActivity());
			   imageAdapter.setImageSize(galleryView.getImageSize());
		}
		imageAdapter.refreshImages(logEntryRepository.getAllLogEntryImages());
		galleryView.setAdapter(imageAdapter);
		galleryView.setOnItemClickListener(imageEditListener);
	}
	
	private void refreshGalleryGridView()
	{
		imageAdapter.refreshImages(logEntryRepository.getAllLogEntryImages());
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
		if (requestCode == REQUEST_DIAGRAM && resultCode == Activity.RESULT_OK)
		{
			// get image data
			String fileName = intent.getStringExtra(Constants.EXTRA_DIAGRAM_FILENAME);           
            boolean deleteDiagram = intent.getBooleanExtra(Constants.EXTRA_DIAGRAM_DELETE, false);
            boolean goToLogEntry = intent.getBooleanExtra(Constants.EXTRA_GOTO_LOG_ENTRY, false);
            
            // deleting current image
            if (deleteDiagram && currentEditedImage != null)
            {
            	showDeleteWarning();
            }

            // updating current image
            if (!deleteDiagram && currentEditedImage != null && fileName != null)
            {
            	updateLogEntryDiagram(fileName);
            }
            
            // goTo the LogEntry
            if (goToLogEntry && currentEditedImage != null)
        	{
        		Bundle args = new Bundle();
        		args.putInt(Constants.EXTRA_LOG_ENTRY_ID, currentEditedImage.getLogEntryId());
        		
        		mListener.onLogEntryEditRequest(args);
        	}
            
		}
		else if (requestCode == REQUEST_VIEW_PHOTO && resultCode == Activity.RESULT_OK)
		{
        	boolean delete = intent.getBooleanExtra(Constants.EXTRA_PHOTO_DELETE, false);
        	boolean goToLogEntry = intent.getBooleanExtra(Constants.EXTRA_GOTO_LOG_ENTRY, false);
        	// deleting current image
        	if (delete && currentEditedImage != null)
        	{
        		showDeleteWarning();
        	}

    		if (goToLogEntry && currentEditedImage != null)
        	{
        		Bundle args = new Bundle();
        		args.putInt(Constants.EXTRA_LOG_ENTRY_ID, currentEditedImage.getLogEntryId());
        		
        		mListener.onLogEntryEditRequest(args);
        	}
        }
	}
	
	private void showDeleteWarning()
	{
		// create alert dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(
				new ContextThemeWrapper(getActivity(), R.style.DialogStyle));
		builder.setMessage(R.string.gallery_image_delete_warning);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(R.string.delete_confirmation);
		
		builder.setPositiveButton(R.string.yes_button, new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int id)
			{
				deleteLogEntryImage();
			}
		});

		builder.setNegativeButton(R.string.no_button, null);
		AlertDialog dialog = builder.create();
		// show dialog
		dialog.show();
	}

	
	private void deleteLogEntryImage()
	{
		LogEntry logEntry = logEntryRepository.getLogEntry(currentEditedImage.getLogEntryId());
		List<LogEntryImage> logEntryImages = logEntry.getImages();
		
		for(int i=0; i<logEntry.getImages().size(); i++)
		{
			if (logEntryImages.get(i).getMD5().equals(currentEditedImage.getMD5()))
			{
				logEntryImages.remove(i);
				break;
			}
		}
		logEntryRepository.updateLogEntry(logEntry);
		refreshGalleryGridView();
	}
	
	private void updateLogEntryDiagram(String filename)
	{
		LogEntry logEntry = logEntryRepository.getLogEntry(currentEditedImage.getLogEntryId());
		List<LogEntryImage> logEntryImages = logEntry.getImages();
		
		for(int i=0; i<logEntry.getImages().size(); i++)
		{
			if (logEntryImages.get(i).getMD5().equals(currentEditedImage.getMD5()))
			{
				logEntryImages.get(i).setFilename(filename);
				logEntryImages.get(i).setMD5(filename.replace(".jpg", ""));
				break;
			}
		}
		logEntryRepository.updateLogEntry(logEntry);
		refreshGalleryGridView();
	}
}